package com.jiong.user.config;

import com.jiong.user.utils.JwtTokenUtils;
import com.auth0.jwt.interfaces.Claim;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@WebFilter(filterName = "JwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("JWT Filter 初始化");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 设置响应编码为 UTF-8
        response.setCharacterEncoding("UTF-8");

        // 获取 Authorization 头部的 Token
        String token = request.getHeader("Authorization");
        String requestPath = request.getRequestURI();

        // 放行登录接口
        if (requestPath.contains("/user/login")) {
            chain.doFilter(request, response);
            return;
        }

        // 放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
            return;
        }

        // 验证 Token 是否存在
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("未提供令牌，请登录");
            return;
        }

        try {
            // 验证 Token 的合法性
            Map<String, Claim> claims = JwtTokenUtils.verifyToken(token);
            if (claims == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("令牌无效，请重新登录");
                return;
            }

            // 提取用户名并设置为请求属性
            String account = claims.get("account").asString();
            if (account == null || account.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("令牌中未包含账户信息");
                return;
            }

            request.setAttribute("account", account);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("令牌解析失败，请重新登录");
            return;
        }

        // 放行请求
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        System.out.println("JWT Filter 销毁");
    }
}